// 新增
/**
 * code: 0 用户名已存在
*/

const searchSql = `SELECT userName FROM members WHERE userName = ?`
const addSql = `INSERT INTO members (userName, phone, projectName, money, age, occupatuin, address) VALUES (?, ?, ?, ?, ?, ?, ?)`


exports.addMember = async function(req, res, next) {

  const {
    userName,
    phone,
    projectName,
    money,
    age,
    occupatuin,
    address
  } = req.body;
  const connection = req.connection;

  // 查询是否有同 用户名  的用户
  // const querySql = `SELECT * FROM members WHERE userName = '${userName}'`;
  try {
    const [ result, fields] = await connection.query(searchSql,[userName]);
    
    if(result.length > 0) {
      // 用户名已存在
      return res.resend.sendJson(req, res, {
        status: 200,
        code: 'FAIL',
        msg: '用户名已存在',
        data: {
          token: req.newToken
        }
      })
    }
    // 用户不存在，新增用户
    const [reu, fie] =  await connection.query(addSql, [userName, phone, projectName, money, age, occupatuin, address]); 
   
    if( reu.affectedRows > 0) {
      return res.resend.sendJson(req, res, {
        status: 200,
        code: 'SUCCESS',
        data: {
          token: req.newToken
        },
        msg: '新增成功'
      })
    }
  }
  catch (err) {
    res.resend.sendJson(req, res, {
      status: 500,
      code: 'FAIL',
      data: '',
      msg: err.message,
      logMsg: err
    })
  }
}